import sys
import os
import time
import smtplib

def mainMail(ycr, parentA, parentB, progenyCount, ypgStart, strainsPerPlate, contact):
	try:
        	msg = {}
        	me = "jlin@systemsbiology.net"#= the sender's email address
        	msg['Subject'] = '%s progeny created' % ycr
        	msg['From'] = "jlin@systemsbiology.net"
        	msg['To'] = contact
        	text = "Some email text"
        	m = "From: %s\r\nTo: %s\r\nSubject: %s\r\nX-Mailer: My-Mail\r\n\r\n" % (me, contact, msg['Subject'])
        # Send the message via our own SMTP server, but don't include the
        # envelope header.
        	s = smtplib.SMTP('mailhost.systemsbiology.net')
        	s.sendmail(msg['From'], [me,contact], m+text)
        	s.quit()
		return '{"status":"200"}'
	except Exception as inst:
		print inst

tetradCount = 1
strainsPerPlate = -1

def executeSH(cmd):
	#cmd = "sh %s" %sh_ypgfile.name
	#print cmd
	os.system(cmd)
	print "done %s" %cmd

def getParents(crosskey):
	print "Get parents for key"

def getSiblings(key):
	remainder = (key-1)%4
	if (remainder == 0):
		return "'YPG%20" + str(key + 1) + "_YPG%20" + str(key + 2) + "_YPG%20" + str(key + 3) + "'"
	elif (remainder == 1):
		return "'YPG%20" + str(key - 1) + "_YPG%20" + str(key + 1) + "_YPG%20" + str(key + 2) + "'"
	elif (remainder == 2):
		return "'YPG%20" + str(key - 1) + "_YPG%20" + str(key - 2) + "_YPG%20" + str(key + 1) + "'"
	else:
		return "'YPG%20" + str(key - 1) + "_YPG%20" + str(key - 2) + "_YPG%20" + str(key - 3) + "'"

def translateRow(offset):
	#print offset
	global strainsPerPlate
	if (offset <= 12):
		return "A"
	if (offset <= 24):
		return "B"
	if (offset <= 36):
		return "C"
	if (offset <= 48):
		return "D"
	if (offset <= 60):
		return "E"
	if (offset <= 72):
		return "F"
	if (offset <= 84):
		return "G"
	if (offset <= strainsPerPlate):
		return "H"

def translateTetradRow():
	#global tetradCount
	if (tetradCount%10 == 0):
		return 10
	return tetradCount%10

def translatePosition(key, boxnum, start, iteration):
	row = translateRow(iteration)
	col = iteration%12 
	if (col == 0):
		col = 12
	return row + str(col)	
	
def translateBoxNumber(ycr, start, key):
	#michelle's plates contain 80 strains, send set begins at 6
	begin = 1
	realkey = key - start
	return realkey/92 + begin

def translatePlateNumber(iteration, start):
	plateNum = 6
	strainsPerPlate = 80
	return plateNum + (iteration/strainsPerPlate)
	
		
def encodeSpace(str):
	return str.replace(' ', '%20')

#python POST.py "http://ravioli:8080/addama-rest/dudley-sample/path/datasource/YPG/YPG%209999/create?JSON={genotype:'ggg',crossingRef:'YCR%208'}"
def generateCreatePosts(crosskey, start, end, perPlate, parentAKey, parentAlphaKey):
	global host, sh_ypgfile, mode, tetradCount, strainsPerPlate
	strainsPerPlate = perPlate
	offset = start
	sh_ypgfile.write("#!/bin/bash\n")
	ypgcsv = open(crosskey + "_ypg.csv", "w")
	ypgcsv.write("ypgKey,ypgMatingType,ypgGenotype,ypgParentA,ypgParentAlpha,ypgSiblings,ypgCrossingRef,ypgBoxNumber,ypgPosition,ypgDateFrozen,ypgComments,ypgTetrad,ypgStatus\n")
	#need to compute box_number, begin with 1, and every 96 strains, increment
	offset = 1
	for ypgkey in range(start, end+1):
		iteration = ypgkey - offset
		if (offset == strainsPerPlate+1):
			offset = 1
		boxnum = translateBoxNumber(crosskey, start, ypgkey)
		ypgcsv.write('"YPG' + str(ypgkey) + '",' + '"Undetermined","","' + parentAKey + '","' + parentAlphaKey + '","","' + crosskey + '",' + crosskey + "-" + str(boxnum) + '",' + '"' + translatePosition(ypgkey, boxnum, start, offset) + '","10/19/2011","","0","Viable"\n'   )
		offset += 1
	sh_ypgfile.close()
	ypgcsv.close()
	#print "done loading crosskey %s" %crosskey
	ccmd = "curl 'http://saskatoon:8080/solr/update/csv?commit=true' --data-binary @" + ypgcsv.name + " -H 'Content-type:text/plain; charset=utf-8'"
	print "run %s" %ccmd
	return "{'status':'200'}" 
	#executeSH('sh ' + sh_ypgfile.name)

if __name__ == "__main__":
	global host, sh_ypgfile, ypgCount, mode
	#if (len(sys.argv) < 8):
	#	print "authorization to host\npy2.6 authorization.py https://ravioli:8443\npython(2.5+) required \npy2.6 YPGForYCR.py host ycrKey ypgKeyStart ypgKeyEnd strainsPerPlate parentAKey parentAlphaKey"
	#	sys.exit(1)
	#else:
	mode = 'create'
	#	host = sys.argv[1]
	#	ypgCount = int(sys.argv[4])
	#	sh_ypgfile = open('./%s_YPG%s_curl.sh' %(mode, 'ycr'+sys.argv[2]),'w')
	ycr = "YCR13"
	parentA = 'YO100'
	parentB = 'YO200'
	start = '10000'
	end = '12000'
	strainsPerPlate = '92'
	generateCreatePosts(sys.argv[2], int(sys.argv[3]),int(sys.argv[4]), int(sys.argv[5]), sys.argv[6], sys.argv[7])
	print mainMail("ycrKey", "parentA", "parentB", "progenyCount", "ypgStart", "strainsPerPlate", "jlin@systemsbiology.org")
		
